package com.ytf.dogbox.dogHttp;




import static com.ytf.dogbox.util.TestConfig.HOST;
import static com.ytf.dogbox.util.TestConfig.httpheader;

import com.ytf.dogbox.util.Log;
import com.ytf.dogbox.util.PreferenceUtil;
import com.ytf.dogbox.util.TestConfig;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;


/** 固件版本下载
 * @author tiwolf_li
 * @Date on 2020/6/23
 * @Description  Post方法
 */
public class DownLoadBoardFile implements Runnable {

    public String TAG="tiwolf";

    private OnThreadResultListener listener;//任务线程回调接口
    File file;

    CountDownLatch downLatch;
    String token;
    int length;


    int mFinished=0;

    double persent=0;

    int totalbyte=0;



    public DownLoadBoardFile(File file, String token, int length, String totalsize, CountDownLatch downLatch, OnThreadResultListener listener){
        this.listener=listener;
        this.downLatch=downLatch;
        this.file=file;
        this.token=token;
        this.length=length;
        this.totalbyte=Integer.valueOf(totalsize);
    }


    @Override
    public void run() {
        PreferenceUtil.commitBoolean(PreferenceUtil.PACKAGEFLAG,true);
        String urlStr= httpheader+HOST+ TestConfig.downloadPackageFile;
        //这里直接进行数据更新。更新下载进度
        RandomAccessFile raf=null;
        HttpURLConnection con=null;
        InputStream is=null;
        try {
//            Log.e(TAG, "download:4未下载的文件下载开始 "+startLength );
            URL url=new URL(urlStr);
            con= (HttpURLConnection) url.openConnection();
            con.setReadTimeout(30000);
            con.setConnectTimeout(30000);
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestMethod("POST");
            con.setRequestProperty("Access-Certificate","Bearer "+token);
            con.setRequestProperty("RANGE","bytes="+length+"-");
            con.setRequestProperty("connection", "Keep-Alive");
            //设置下载位置
            int start=length;
            mFinished=start;
//            con.setRequestProperty("Range", "bytes=" + start + "-" + downloadItem.getDownloadEnd());
            //设置一个文件写入位置
            raf=new RandomAccessFile(file,"rwd");
            //设置文件写入位置
            raf.seek(start);

//            mFinished+=downloadItem.getDownloadFinish()*con.getContentLength()/100;
            //开始下载
            if (con.getResponseCode()== HttpURLConnection.HTTP_OK){
                //读取数据
                is=con.getInputStream();
                byte[] buffer=new byte[1024*512];
                int len=-1;
                while ((len=is.read(buffer))!=-1){
                    //写入文件
                    raf.write(buffer,0,len);
                    start+=len;
                    mFinished=start;
//                    Log.e(TAG, "已经下载了: "+mFinished+"字节" );
                    PreferenceUtil.commitInt(PreferenceUtil.BOARDLENGTH,mFinished);
                    persent=(mFinished/(double)totalbyte)*100;
//                    Log.e(TAG, "文件的大小为"+totalbyte );
//                    Log.e(TAG, "已经下载了百分比: "+persent );

                    listener.onBoardProgressChange((int)persent);

                }
//                Log.e("tiwolf1111", "run: 下载完成了" );
                PreferenceUtil.commitInt(PreferenceUtil.BOARDLENGTH,0);
                listener.onBoardDownloadSuccess();
                Log.e(TAG, "run: 下载完成,总的字节为:"+start );
            }else{
                PreferenceUtil.commitBoolean(PreferenceUtil.PACKAGEFLAG,false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "run: 下载异常，当前下载进度为"+mFinished);
            PreferenceUtil.commitBoolean(PreferenceUtil.PACKAGEFLAG,false);
//            Log.e(TAG, "download:7未下载的文件下载异常 " );
            PreferenceUtil.commitInt(PreferenceUtil.BOARDLENGTH,mFinished);
            listener.onBoardDownloadFail();

        }finally {
            PreferenceUtil.commitBoolean(PreferenceUtil.PACKAGEFLAG,false);
            try {
                if (con!=null){
                    con.disconnect();
                }
                if (raf!=null){
                    raf.close();
                }
                if (is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        downLatch.countDown();
    }
}
